<?php

declare(strict_types=1);

namespace App\CustHub\Mapper;

use App\CustHub\Model\ChRoomTag;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Model;
use Mine\Abstracts\AbstractMapper;

class ChRoomTagMapper extends AbstractMapper
{
    public function assignModel()
    {
        $this->model = ChRoomTag::class;
    }

    /**
     * @param mixed $id
     * @return ChRoomTag|Model|string|Builder|null
     */
    public function findById(mixed $id): ChRoomTag|Model|string|Builder|null
    {
        return $this->model::query()->where('id',$id)->first();
    }

    /**
     * 根据id获取标签名称
     * @param array $ids
     * @return array
     */
    public function getNameByIds(array $ids): array
    {
        return $this->model::query()->whereIn('id',$ids)->pluck('name')->toArray();
    }

    /**
     * 检查标签名称是否已存在
     * @param string $name
     * @param mixed $id
     * @return bool
     */
    public function checkExistByName(mixed $mainUid,string $name,mixed $parentId = null,mixed $id = null): bool
    {
        return $this->model::query()
            ->where('main_uid',$mainUid)
            ->when(filled($id),function ($query) use ($id){
                $query->where('id','<>',$id);
            })
            ->when(filled($parentId),function ($query) use ($id,$parentId){
                $query->where('parent_id',$parentId);
            })
            ->where('name',$name)
            ->exists();
    }

    /**
     * 根据模块获取标签数量
     * @param mixed $mainUid
     * @param mixed|null $parentId
     * @return int
     */
    public function getCount(mixed $mainUid,mixed $parentId = null): int
    {
        return $this->model::query()
            ->where('main_uid',$mainUid)
            ->when(filled($parentId),function ($query) use ($parentId){
                $query->where('parent_id',$parentId);
            })
            ->count();
    }
}